package com.iyundao.io.controller;

import com.iyundao.io.tools.ImageUtils;
import com.iyundao.io.tools.ResponseData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * 上传接口
 *
 * @author inkfeather
 * @date 2019/05/05
 */
@RestController
@RequestMapping(value = "/upload")
public class ImageUploadController {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    /**
     * 上传操作
     * @param file
     *      图片文件
     * @return
     *      图片保存路径
     */
    @RequestMapping(value = "/upload")
    public String ActivityImageUpload(@RequestParam( value="files",required=false ) MultipartFile file) {
        if (file.isEmpty()) {
            return "上传文件失败，请选择文件";
        }

        //获取图片名
        String fileName = String.valueOf(System.currentTimeMillis())+".jpg";

        //图片路径
        File dest = new File(uploadFolder +"/images/"+ fileName);

        if(!dest.exists()){
            //先得到文件的上级目录，并创建上级目录，在创建文件
            dest.getParentFile().mkdirs();
            try {
                //创建文件
                dest.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            //图片上传
            file.transferTo(dest);
            //将原图替换为缩略图
            Boolean aBoolean = ImageUtils.createThumbnail(dest, dest, 500, 500);
            if (aBoolean) {
                //return "http://129.211.47.17:8080/frame/upload/images/" + fileName;
                return "https://www.ydyy.online/frame/upload/images/" + fileName;

            } else {
                return "添加缩略图失败";
            }
        } catch (IOException e) {
            return e.getMessage();
        }

    }

}
